#coding:utf-8

import socket, thread, select
from urllib2 import urlopen 

import urllib2

enable_proxy = True

proxy_handler = urllib2.ProxyHandler({"http" : 'http://127.0.0.1:8080'})

null_proxy_handler = urllib2.ProxyHandler({})

if enable_proxy:

    opener = urllib2.build_opener(proxy_handler)

else:

    opener = urllib2.build_opener(null_proxy_handler)

urllib2.install_opener(opener)

httpHandler = urllib2.HTTPHandler(debuglevel=1)

httpsHandler = urllib2.HTTPSHandler(debuglevel=1)

opener = urllib2.build_opener(httpHandler, httpsHandler)

urllib2.install_opener(opener)




__version__ = '0.1.0 Draft 1'
BUFLEN = 8192
VERSION = 'Python Proxy/'+__version__
HTTPVER = 'HTTP/1.1'

class ConnectionHandler:
    def __init__(self, connection, address, timeout):
        self.client = connection
        self.client_buffer = {}
        self.timeout = timeout
        self.method, self.path, self.protocol = self.get_base_header()
        print '-------------------------'
        print self.method,'@' ,self.path,'@', self.protocol ,'@',self.client_buffer
        print '---------------------------------------'
        # if 
        # del self.client_buffer['Accept-Encoding']

        request = urllib2.Request( self.path,headers = {})

        res = urlopen(request) 

        html = res.read()
        self.client.send(html)

        res.close() 
  
        self.client_buffer = ''
        #if self.method=='CONNECT':
        #     self.method_CONNECT()
        #elif self.method in ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT',
        #                      'DELETE', 'TRACE'):
        #     #self.method_others()
        #     pass
        #self.client.close()
        #self.target.close()

    def get_base_header(self):
        self.client_buffe={}
        self.client_buffer=''
        while 1:
            self.client_buffer += self.client.recv(BUFLEN)
            end = self.client_buffer.find('\n')
            if end!=-1:
                break
       
        data = (self.client_buffer[:end+1]).split()
        self.client_buffer = self.client_buffer[end+1:]
        # for d in client_buffer.split("\n"):
            # if ':' in d:
            #     k,v=d.split(":")
            #     self.client_buffer[k]=v
        return data

    def method_CONNECT(self):
        self._connect_target(self.path)
        self.client.send(HTTPVER+' 200 Connection established\n'+
                         'Proxy-agent: %s\n\n'%VERSION)
        self.client_buffer = ''
        self._read_write()        
 
    def method_others(self):
        self.path = self.path[7:]
        i = self.path.find('/')
        host = self.path[:i]        
        path = self.path[i:]
        self._connect_target(host)
        self.target.send('%s %s %s\n'%(self.method, path, self.protocol)+
                         self.client_buffer)


        #Debug Log end

        request = urllib2.Request("http://www.0791quanquan.com/",headers = self.client_buffer)

        res = urlopen(request) 

        html = res.read()
        print html

        res.close() 
  
        self.client_buffer = ''
        # self._read_write()

    def _connect_target(self, host):
        i = host.find(':')
        if i!=-1:
            port = int(host[i+1:])
            host = host[:i]
        else:
            port = 80
        (soc_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
        self.target = socket.socket(soc_family)
        print address
        self.target.connect(('127.0.0.1',8080))

    def _read_write(self):
        time_out_max = self.timeout/3
        socs = [self.client, self.target]
        count = 0
        while 1:
            count += 1
            (recv, _, error) = select.select(socs, [], socs, 3)
            if error:
                break
            if recv:
                for in_ in recv:
                    data = in_.recv(BUFLEN)
                    if in_ is self.client:
                        out = self.target
                    else:
                        out = self.client
                    if data:
                        out.send(data)
                        count = 0
            if count == time_out_max:
                break

def start_server(host='127.0.0.1', port=8083, IPv6=False, timeout=60,
                  handler=ConnectionHandler):
    if IPv6==True:
        soc_type=socket.AF_INET6
    else:
        soc_type=socket.AF_INET
    soc = socket.socket(soc_type)
    soc.bind((host, port))
    print "Serving on %s:%d."%(host, port)#debug
    soc.listen(0)
    while 1:
        thread.start_new_thread(handler, soc.accept()+(timeout,))

if __name__ == '__main__':
    start_server()
